package com.yuhanginfo.modules.sys.service;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


import com.yuhanginfo.common.persistence.Page;
import com.yuhanginfo.common.service.CrudService;
import com.yuhanginfo.modules.sys.entity.Credit;
import com.yuhanginfo.modules.sys.entity.Orders;
import com.yuhanginfo.modules.sys.entity.OrdersDetail;
import com.yuhanginfo.modules.sys.entity.ReturnGoodsDetail;
import com.yuhanginfo.modules.sys.entity.ReturnsGoods;
import com.yuhanginfo.modules.sys.entity.TransactionHistory;
import com.yuhanginfo.modules.sys.entity.User;
import com.yuhanginfo.modules.sys.utils.CodeUtil;
import com.yuhanginfo.modules.sys.utils.UserUtils;
import com.yuhanginfo.modules.sys.customexception.CustomException;
import com.yuhanginfo.modules.sys.dao.CreditDao;
import com.yuhanginfo.modules.sys.dao.OrdersDao;
import com.yuhanginfo.modules.sys.dao.OrdersDetailDao;
import com.yuhanginfo.modules.sys.dao.ReturnGoodsDetailDao;
import com.yuhanginfo.modules.sys.dao.ReturnsGoodsDao;
import com.yuhanginfo.modules.sys.dao.TransactionHistoryDao;

/**
 * 订单变更Service
 * 
 * @author yinhao
 * @version 2017-10-13
 */
@Service
@Transactional(readOnly = true)
public class OrdersExchangeService extends CrudService<OrdersDao, Orders> {
	public static final Logger logger =  LoggerFactory.getLogger(OrdersExchangeService.class);
	@Autowired
	private OrdersDao ordersDao;

	@Autowired
	private OrdersDetailDao ordersDetailDao;

	@Autowired
	private ReturnsGoodsDao returnsGoodsDao;
	
	@Autowired
	private ReturnGoodsDetailDao returnGoodsDetailDao;
	
	@Autowired
	private CreditDao creditDao;
	
	@Autowired
	private TransactionHistoryDao transactionHistoryDao;
	

	
	

	public Map<String, Object> findDetailCount(Orders orders) throws CustomException {
		Map<String, Object> resultMap = new HashMap<>();
		Orders ordersResult = ordersDao.getByCode(orders);
	
		resultMap.put("orders", ordersResult);
		OrdersDetail queryOrdersDetail = new OrdersDetail();
		queryOrdersDetail.setOrdersCode(orders.getCode());
		if("1".equals(ordersResult.getOrderType()) || "3".equals(ordersResult.getOrderType())){
			resultMap.put("detailCount", ordersDetailDao.findAll(queryOrdersDetail));
		}else if("2".equals(ordersResult.getOrderType())){
			resultMap.put("detailCount", ordersDetailDao.findAllCombo(queryOrdersDetail));
		}else{
			resultMap.put("resultCode", "0");
			resultMap.put("resultMessage", "order_type错误");
		}
		
		return resultMap;
	}

	public Page<Orders> findPage(Page<Orders> page, Orders orders) {
		orders.setPage(page);
		page.setList(ordersDao.findOrdersExchangeList(orders));
		return page;
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void save(String type,String userId,String ordersCode,String ordersPayType,String[] goodsCnName,String[] goodsCode,String[] num,String[] money,String remarks) throws Exception {
		Date now = new Date();
		User user = UserUtils.getUser();
		try{
			ReturnsGoods returnsGoods = new ReturnsGoods();
			String returnCode = CodeUtil.getReturnsGoodsCode(ordersCode);
			returnsGoods.setReturnCode(returnCode);
			returnsGoods.setOrderCode(ordersCode);
			returnsGoods.setReturnUserId("1");
			returnsGoods.setType(type);
			returnsGoods.setUserId(userId);
			returnsGoods.setReason(remarks);
			returnsGoods.setCreateBy(user);
			returnsGoods.setCreateDate(now);
			returnsGoods.setUpdateBy(user);
			returnsGoods.setUpdateDate(now);
			returnsGoodsDao.insert(returnsGoods);
			//
			int totalMoney = 0;
			List<ReturnGoodsDetail> insertList = new ArrayList<>();
			for(int i=0;i<num.length;i++){
				if(!"0".equals(num[i])){
					totalMoney += Integer.parseInt(money[i]);
					ReturnGoodsDetail returnGoodsDetail = new ReturnGoodsDetail();
					returnGoodsDetail.setReturnCode(returnCode);
					returnGoodsDetail.setGoodsCode(goodsCode[i]);
					returnGoodsDetail.setGoodsName(goodsCnName[i]);
					returnGoodsDetail.setNum(num[i]);
					returnGoodsDetail.setMoney(money[i]);
					returnGoodsDetail.setCreateBy(user);
					returnGoodsDetail.setCreateDate(now);
					returnGoodsDetail.setUpdateBy(user);
					returnGoodsDetail.setUpdateDate(now);
					insertList.add(returnGoodsDetail);
				}
			}
			returnGoodsDetailDao.batchInsert(insertList);
//			//记录交易记录
			TransactionHistory transactionHistory = new TransactionHistory();
			transactionHistory.setUserId(userId);

			transactionHistory.setCode(ordersCode);

			transactionHistory.setType("4");
			transactionHistory.setPayType(Integer.valueOf(ordersPayType));
			transactionHistory.setMoney(new BigDecimal(totalMoney));
			transactionHistory.setCreateBy(user);
			transactionHistory.setCreateDate(now);
			transactionHistory.setUpdateBy(user);
			transactionHistory.setUpdateDate(now);
			transactionHistory.setRemarks(remarks);
			transactionHistoryDao.insert(transactionHistory);
			//如果金额不为0,改变信用额度
			if(totalMoney != 0){
				Credit queryCredit = creditDao.selectByUserId(userId);
				if(queryCredit == null){
					return;
				}
				Credit updateCredit = new Credit();
				updateCredit.setUserId(userId);
				if("1".equals(type)){//如果是退货则算到用户充值额度
					if(queryCredit.getRechargeMoney() == null){
						queryCredit.setRechargeMoney(new BigDecimal(0));
					}
					updateCredit.setRechargeMoney(queryCredit.getRechargeMoney().add(new BigDecimal(totalMoney)));
				
				}
				creditDao.updateByUserId(updateCredit);
			}
		}catch(Exception ex){
			logger.debug("",ex);
		}
	}

}